package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.StringUtil;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        String email = user.getEmail();
        if (!StringUtil.hasLength(email)) {
            throw new RuntimeException("邮箱不能为空");
        }
        User temp = userMapper.selectUserByEmailAndPassword(email, null);
        if (temp != null) {
            throw new RuntimeException("邮箱已注册!");
        }
        user.setCoverImgUrl("/img/user/bg.jpeg");
        user.setHeadImgUrl("/img/user/head.jpg");
        userMapper.insert(user);
    }

    @Override
    public User login(User user) {
        String email = user.getEmail();
        String password = user.getPassword();
        if (StringUtil.hasLength(email) && StringUtil.hasLength(password)){
            User temp = userMapper.selectUserByEmailAndPassword(email, password);
            if (temp == null) {
                throw new RuntimeException("邮箱或密码有误!");
            }
            UserContext.setCurrentUser(temp);
            return temp;
        }
        throw new RuntimeException("邮箱或密码不能为空!");
    }

    @Override
    public void update(User user) {
        if (user != null) {
            userMapper.updateByPrimaryKey(user);
        }
    }

    @Override
    public PageInfo<User> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<User> list = userMapper.selectForList(qo);
        return new PageInfo<User>(list);
    }

    @Override
    public User get(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }
}
